package com.ling.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.ling.springbootinit.common.*;
import com.ling.springbootinit.exception.BusinessException;
import com.ling.springbootinit.mapper.SongMapper;
import com.ling.springbootinit.model.dto.song.*;
import com.ling.springbootinit.model.entity.Song;
import com.ling.springbootinit.service.WeatherService;
import com.ling.springbootinit.utils.RandomUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * song

 */
@RestController
@RequestMapping("/song")
@Slf4j
public class SongController {

    @Resource
    private WeatherService weatherService;
    @Resource
    private SongMapper songMapper;


    /**
     1:歌曲搜索接口
     请求地址: /search
     请求方法:get
     请求参数:keywords(查询关键字)
     响应内容:歌曲搜索结果
     */
    @GetMapping("/search")
    public SongResponse<SongRespVO> searchSongByKeywords(String keywords) {

        QueryWrapper<Song> queryWrapper = new QueryWrapper<Song>();
        //name不为空时，组装模糊查询条件
        queryWrapper.like(StringUtils.isNotBlank(keywords), "name",keywords);
        List<Song> songList = songMapper.selectList(queryWrapper);

        SongRespVO respVO = new SongRespVO();
        respVO.setSongs(songList);
        respVO.setSongCount((long) songList.size());

        return ResultUtils.successSong(respVO);
    }

    private static final String BASE_PATH = System.getProperty("user.dir") + "/src/main/resources/media/";
    // D:\soft\develop\idea\pros\my\vuetest-interface\src\main\resources\media文件夹下的文件。

/**
   4.热门评论获取
    请求地址:/comment/hot?type=0
    请求方法:get
    请求参数:id(歌曲id,地址中的type固定为0)
    响应内容:歌曲的热门评论
    */

    @GetMapping("/comment/hot")
    public SongCommentResponse<List<HotCommentRespVO>, List<String>> getCommentHot(int type, Long id) {
        List<String> topComments = new ArrayList<>(); //空list
        List<HotCommentRespVO> hotComments = new ArrayList<>();
        for (int i = 0; i<10; i++) {
            HotCommentRespVO respVO = mockHotCommentRespVO(i, id);
            hotComments.add(respVO);
        }

//   public static <T,E> SongCommentResponse<T, E> successSongC(T hotComments, E topComments, int total) {
//        return new SongCommentResponse<>(0, true, hotComments, topComments,total);}
        return ResultUtils.successSongC(hotComments,topComments,10);
    }

    /**
     5.mv地址获取
     请求地址:/mv/url
     请求方法:get
     请求参数:id(mvid,为0表示没有mv)
     响应内容:mv的地址
     */
    private static int random1or2 = 1;

    @GetMapping("/mv/url")
    public BaseResponse<MvUrlRespVO> getMvUrl(Long id) {
        MvUrlRespVO mvUrlRespVO = new MvUrlRespVO();
        mvUrlRespVO.setCode(200);
        mvUrlRespVO.setExpi(RandomUtils.getRandomInt(4));
        mvUrlRespVO.setFee(0);
        mvUrlRespVO.setId(id);
        mvUrlRespVO.setMd5("");
        mvUrlRespVO.setMsg("");
        mvUrlRespVO.setMvFee(0);
        mvUrlRespVO.setR(RandomUtils.getRandomInt(4));
        mvUrlRespVO.setSize(RandomUtils.getRandomLong(9));
        mvUrlRespVO.setSt(0);

        String baseUrl = "http://localhost:8101/api/upload/1";
        // http://localhost:8101/api/upload/16880.mp4
        String path = baseUrl + random1or2 + ".mp4";
        if(random1or2 ==1){ //1与2之间互换。
            random1or2 =2;
        }else {
            random1or2 =1;
        }
        mvUrlRespVO.setUrl(path);
        return ResultUtils.success(mvUrlRespVO);
    }


    /**
     * 3.歌曲详情获取
     * 请求地址: /song/detail
     * 请求方法:get
     * 请求参数:ids(歌曲id)
     * 响应内容:歌曲详情(包括封面信息)
     */

    @GetMapping("/detail")
    public SongDetailResponse<List<Song>, List<SongDetailRespVO>> getSongDetail(String ids) {
//// - 2.歌曲地址获取(接口歌曲id) 从data中data的0的url得到的。
//// - 3.歌曲地址设置(v-bind)
//    console.log(musicId);
//    axios.get("http://localhost:8101/api/song/url?id=" + musicId)
        List<Song> privileges = new ArrayList<>();
        Song song = mockSongObject();
        privileges.add(song);

        List<SongDetailRespVO> songs = new ArrayList<>();
        SongDetailRespVO songDetailObject = mockSongDetailObject(ids);
        songs.add(songDetailObject);

        return ResultUtils.successSongD(privileges,songs);// 正常播放
    }

    /**
     * 生成一个Song对象
     */
    private Song mockSongObject(){
        Song song = new Song();
        song.setId(0L);
        song.setName("歌曲");
        song.setMvId(0L);
        song.setCreateTime(new Date());
        song.setUpdateTime(new Date());
        song.setIsDelete(0);
        return song;
    }



    /**
     *   2:歌曲url获取接口
     *     请求地址: /song/url
     *     请求方法:get
     *     请求参数:id(歌曲id)
     *     响应内容:歌曲url地址
     */

    @GetMapping("/url")
    public BaseResponse<List<SongUrlRespVO>> getSongUrl(String id) {
//// - 2.歌曲地址获取(接口歌曲id) 从data中data的0的url得到的。
//// - 3.歌曲地址设置(v-bind)
//    console.log(musicId);
//    axios.get("http://localhost:8101/api/song/url?id=" + musicId)
        List<SongUrlRespVO> respVOList = new ArrayList<>();


        SongUrlRespVO respVO = new SongUrlRespVO();

// url 设置。因为只有2个MP3文件。
        if(Integer.parseInt(id) < 100){
            id = "16880";
        }else {
            id = "16890";
        }

        String baseUrl = "http://localhost:8101/api/upload/";
        // D:/vuetest-interface/src/main/resources/media/16890.mp3
        // 正确的访问路径：http://localhost:8101/api/upload/16880.txt
        // http://localhost:8101/api/upload/16880.mp3
        String path = baseUrl + id + ".mp3";
        respVO.setUrl(path);
        respVO.setBr(12800);
        respVO.setEncodeType("mp3");
        respVO.setSize(418756);
        respVO.setFee(8);
        respVO.setLevel("standard");
        respVOList.add(respVO);
        return ResultUtils.success(respVOList);// 正常播放
    }

   @GetMapping("/urlById")
    public ResponseEntity<byte[]> getSongByUrlId(String id) {
//    public void getSongByUrlId(String id) {

       if(Integer.parseInt(id) < 100){
           id = "16880";
       }else {
           id = "16890";
       }
        File file = new File(BASE_PATH + id + ".mp3"); //文件名拼接
        byte[] plays = null;
        // 找到路径下的文件进行读取
        //plays = Files.readAllBytes(file.toPath());
        plays = FileUtil.readBytes(file.toPath());
        // 若未获取文件, 返回一个错误请求
        if (plays == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_File);
        }
        return ResponseEntity.ok(plays);// 正常播放

    }


//   测试，根据name获取模糊查询 song
    @GetMapping("/getOneByName")
    public BaseResponse<List<Song>> getOneByName(String name) {
    QueryWrapper<Song> queryWrapper = new QueryWrapper<Song>();
    //name不为空时，组装模糊查询条件

    /*  在使用Mybatis-Plus的QueryWrapper进行模糊查询时，可以使用like方法来实现。
like(boolean condition, R column, Object val)
当第一个参数为true时，表示要进行模糊查询，当第一个参数为false时，表示不进行模糊查询。
第二个参数是要进行模糊查询的属性名。通过这种方式，我们可以根据需要动态地决定是否进行模糊查询。
例如，我们可以使用StringUtils.isNotBlank方法来判断用户输入的模糊查询条件是否为空，
如果不为空，就模糊查询；为空，就不进行模糊查询。  */
    queryWrapper.like(StringUtils.isNotBlank(name), "name",name);
    List<Song> songList = songMapper.selectList(queryWrapper);
        return ResultUtils.success(songList);
    }


    /**
     * 生成一个SongDetailRespVO对象
     */
    private HotCommentRespVO mockHotCommentRespVO(int order, Long id){

        HotCommentRespVO hotComment = new HotCommentRespVO();
        hotComment.setBeReplied(Lists.newArrayList());
//        new
        Long aLong = RandomUtils.getRandomLong(7);
        hotComment.setCommentId(aLong +id);
        hotComment.setCommentLocationType(0);
        String s = RandomUtils.getRandomString(6);
        hotComment.setContent("非常好听" + aLong);

        hotComment.setDecoration(null);
        hotComment.setExpressionUrl(null);
        hotComment.setLiked(false);
        hotComment.setLikedCount(RandomUtils.getRandomLong(6));
        hotComment.setParentCommentId(0);
        hotComment.setPendantData(Lists.newArrayList());
        hotComment.setStatus(0);
        hotComment.setTime(System.currentTimeMillis());
        CommentUser commentUser = mockCommentUser(order, id);
        hotComment.setUser(commentUser);
        return hotComment;
    }

    /**
     * 生成一个 CommentUser对象
     */
    private CommentUser mockCommentUser(int order, Long id){

        CommentUser commentUser = new CommentUser();
        commentUser.setAuthStatus(1);
        //图片的path
        String baseUrl = "http://localhost:8101/api/pic/user";
        // D:/vuetest-interface/src/main/resources/pic/11.jpg
        // 正确的访问路径：http://localhost:8101/api/pic/user0.jpg
        String path = baseUrl + order + ".jpg";  //order从0到9
        commentUser.setAvatarUrl(path);
        commentUser.setExpertTags(null);
        commentUser.setLocationInfo("同城");
        commentUser.setNickname(RandomUtils.getRandomName());
        commentUser.setRemarkName(null);
        commentUser.setUserId(RandomUtils.getRandomLong(8) +id);
        commentUser.setUserType(4);
        commentUser.setVipType(11);
        return commentUser;
    }


    /**
     * 生成一个SongDetailRespVO对象
     */
    private SongDetailRespVO mockSongDetailObject(String ids){
        SongDetailAl al = mockSongDetailAl(ids);

        SongDetailRespVO detailResp = new SongDetailRespVO();
        detailResp.setA(null);
        detailResp.setAl(al);
        detailResp.setAlia(new SongDetailAlia());
        detailResp.setAr(new SongDetailAr());
        detailResp.setCd("01");
        detailResp.setCf("");
        detailResp.setCopyright(1);
        detailResp.setCp(21001);
        detailResp.setCrbt(null);
        detailResp.setDjId(0);
        return detailResp;
    }


    /**
     * 生成一个SongDetailAl对象
     */
    private SongDetailAl mockSongDetailAl(String ids){
        SongDetailAl al = new SongDetailAl();
        al.setId(0L);
        al.setName("歌曲");
        //生成1-9的随机数
        Random random = new Random();
        int value = random.nextInt(9) + 1;
        value+=10;
        System.out.println(value);
        al.setPic((long) value);
        //图片的path
        String baseUrl = "http://localhost:8101/api/pic/";
        // D:/vuetest-interface/src/main/resources/pic/11.jpg
        // 正确的访问路径：http://localhost:8101/api/pic/11.jpg
        String path = baseUrl + value + ".jpg";
        al.setPicUrl(path);
        al.setPic_str(ids+ value);
        al.setTns(Lists.newArrayList());
        return al;
    }

}
